package com.firstspring.test;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Configuration;

//@Configuration
public class TomcatConfig {
    /**
     * 设置Tomcat的Server配置
     *
     * @return
     */
    TomcatServletWebServerFactory tomcatServletWebServerFactory() {
        TomcatServletWebServerFactory myFactory = new TomcatServletWebServerFactory() {
            protected void postProcessContext(Context context) {
                // 创建一个安全约束对象
                SecurityConstraint my_constraint = new SecurityConstraint();
                my_constraint.setUserConstraint("CONFIDENTIAL"); // 设置为机密级别
                SecurityCollection my_connection = new SecurityCollection(); // 创建一个安全连接对象
                // 作用到所有路由上
                my_connection.addPattern("/*");
                // 加入connection对象到安全约束对象中
                my_constraint.addCollection(my_connection);

                context.addConstraint(my_constraint);
            }
        };

        myFactory.addAdditionalTomcatConnectors(createConnector());
        return myFactory;
    }

    /**
     * 创建一个连接，兼容http请求
     *
     * @return
     */
    private Connector createConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.HttpNioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false); // 关闭ssl检查
        //设置跳转到8081的端口
        connector.setRedirectPort(8081);
        return connector;
    }
}
